import logging
import sys
from typing import Optional, Union, Dict, Any
import os
from datetime import datetime

# 配置日志格式
LOG_FORMAT = "%(asctime)s [%(levelname)s] [%(name)s] %(message)s"
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

# 日志级别映射
LOG_LEVELS = {
    "debug": logging.DEBUG,
    "info": logging.INFO,
    "warning": logging.WARNING,
    "error": logging.ERROR,
    "critical": logging.CRITICAL
}

# 默认日志级别（可从环境变量获取）
DEFAULT_LOG_LEVEL = os.environ.get("LOG_LEVEL", "info").lower()


class Logger:
    """
    统一的日志记录器类，提供一致的日志接口
    """
    
    _loggers: Dict[str, logging.Logger] = {}
    
    @classmethod
    def get_logger(cls, name: str) -> logging.Logger:
        """
        获取或创建一个命名的日志记录器
        
        Args:
            name: 日志记录器名称，通常是模块名
            
        Returns:
            配置好的日志记录器
        """
        if name in cls._loggers:
            return cls._loggers[name]
        
        # 创建新的日志记录器
        logger = logging.getLogger(name)
        
        # 设置日志级别
        log_level = LOG_LEVELS.get(DEFAULT_LOG_LEVEL, logging.INFO)
        logger.setLevel(log_level)
        
        # 添加控制台处理器
        if not logger.handlers:
            handler = logging.StreamHandler(sys.stdout)
            handler.setFormatter(logging.Formatter(LOG_FORMAT, DATE_FORMAT))
            logger.addHandler(handler)
        
        # 缓存日志记录器
        cls._loggers[name] = logger
        return logger


def get_logger(name: str) -> logging.Logger:
    """
    获取命名的日志记录器的便捷函数
    
    Args:
        name: 日志记录器名称，通常是模块名
        
    Returns:
        配置好的日志记录器
    """
    return Logger.get_logger(name)


# 为了方便使用，提供直接的日志函数
def debug(name: str, message: str, *args, **kwargs):
    """记录调试级别日志"""
    get_logger(name).debug(message, *args, **kwargs)


def info(name: str, message: str, *args, **kwargs):
    """记录信息级别日志"""
    get_logger(name).info(message, *args, **kwargs)


def warning(name: str, message: str, *args, **kwargs):
    """记录警告级别日志"""
    get_logger(name).warning(message, *args, **kwargs)


def error(name: str, message: str, *args, **kwargs):
    """记录错误级别日志"""
    get_logger(name).error(message, *args, **kwargs)


def critical(name: str, message: str, *args, **kwargs):
    """记录严重错误级别日志"""
    get_logger(name).critical(message, *args, **kwargs)